package com.eden.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.eden.config.Configuration;
import com.eden.constant.Constant;
import com.eden.constant.Constant_msg;
import com.eden.context.AppContext;
import com.eden.service.AnalyzeService;
import com.eden.service.ChartService;
import com.eden.service.ExcelService;
import com.eden.ui.Model;
import com.eden.util.MessageUtil;

public class MainView extends JFrame {
	private static final long serialVersionUID = 1L;
	private static Log log = LogFactory.getLog(MainView.class) ;

	private ExcelService excelService ;
	private AnalyzeService analyzeService ;
	private ChartService chartService ;
	
	private JPanel contentPane;
	private JPanel mainPanel;
	private JTextField subjectField;
	private JTextField classField;
	private JTextField fileNameField;
	private JButton setupButton;
	private JButton analyzeButton;
	private JButton openButton;
	private JButton inputButton;
	
	private String subjectName ;
	private String className ;

	private JFileChooser fChooser;
//	当前处理的文件
	private File currFile ;
	
	private MainView self ;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainView frame = new MainView();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public void init(){
		fChooser = new JFileChooser();
		fChooser.removeChoosableFileFilter(fChooser.getFileFilter() ) ;
		fChooser.addChoosableFileFilter(new FileNameExtensionFilter("office", "xls")) ;
	}
	/**
	 * Create the frame.
	 */
	public MainView() {
		
		try{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) ;
		} catch(Exception e) {
			e.printStackTrace() ;
			log.warn("set UI error..." + e) ;
		}
		init() ;
		self = this ;
		setResizable(false) ;
		setTitle("成绩分析");
		setIconImage(Toolkit.getDefaultToolkit().getImage("D:\\workspaces\\Eclipse\\ScoreAnalyze\\image\\ico.png"));
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 749, 506);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		
		mainPanel = new JPanel();
		contentPane.add(mainPanel);
		mainPanel.setLayout(null);
		
		JPanel panel = new JPanel();
		panel.setBounds(0, 0, 734, 70);
		mainPanel.add(panel);
		panel.setLayout(null);
		
		JLabel lblNewLabel = new JLabel("New label");
		lblNewLabel.setIcon(new ImageIcon("D:\\workspaces\\Eclipse\\ScoreAnalyze\\image\\frameBack.jpg"));
		lblNewLabel.setBounds(0, 0, 734, 70);
		panel.add(lblNewLabel);
		
		JLabel lblNewLabel_1 = new JLabel("成 绩 分 析 系 统");
		lblNewLabel_1.setBorder(new LineBorder(new Color(169, 169, 169)));
		lblNewLabel_1.setBackground(Color.PINK);
		lblNewLabel_1.setForeground(new Color(107, 142, 35));
		lblNewLabel_1.setFont(new Font("微软雅黑", Font.PLAIN, 24));
		lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
		lblNewLabel_1.setBounds(175, 80, 382, 57);
		mainPanel.add(lblNewLabel_1);
		
		JPanel inputPanel = new JPanel();
		inputPanel.setBounds(175, 192, 382, 100);
		mainPanel.add(inputPanel);
		GridBagLayout gbl_inputPanel = new GridBagLayout();
		gbl_inputPanel.columnWidths = new int[]{102, 235, 0};
		gbl_inputPanel.rowHeights = new int[]{30, 27, 0, 0};
		gbl_inputPanel.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
		gbl_inputPanel.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
		inputPanel.setLayout(gbl_inputPanel);
		
		JLabel subjectLabel = new JLabel("课程名称");
		GridBagConstraints gbc_subjectLabel = new GridBagConstraints();
		gbc_subjectLabel.fill = GridBagConstraints.BOTH;
		gbc_subjectLabel.insets = new Insets(0, 0, 5, 5);
		gbc_subjectLabel.gridx = 0;
		gbc_subjectLabel.gridy = 0;
		inputPanel.add(subjectLabel, gbc_subjectLabel);
		
		subjectField = new JTextField();
		GridBagConstraints gbc_subjectField = new GridBagConstraints();
		gbc_subjectField.fill = GridBagConstraints.BOTH;
		gbc_subjectField.insets = new Insets(0, 0, 5, 0);
		gbc_subjectField.gridx = 1;
		gbc_subjectField.gridy = 0;
		inputPanel.add(subjectField, gbc_subjectField);
		subjectField.setColumns(10);
		
		JLabel classLabel = new JLabel("班级名称");
		GridBagConstraints gbc_classLabel = new GridBagConstraints();
		gbc_classLabel.fill = GridBagConstraints.BOTH;
		gbc_classLabel.insets = new Insets(0, 0, 5, 5);
		gbc_classLabel.gridx = 0;
		gbc_classLabel.gridy = 1;
		inputPanel.add(classLabel, gbc_classLabel);
		
		classField = new JTextField();
		GridBagConstraints gbc_classField = new GridBagConstraints();
		gbc_classField.insets = new Insets(0, 0, 5, 0);
		gbc_classField.fill = GridBagConstraints.BOTH;
		gbc_classField.gridx = 1;
		gbc_classField.gridy = 1;
		inputPanel.add(classField, gbc_classField);
		classField.setColumns(10);
		
		JLabel label = new JLabel("文件位置");
		label.setHorizontalTextPosition(SwingConstants.LEFT);
		label.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_label = new GridBagConstraints();
		gbc_label.anchor = GridBagConstraints.WEST;
		gbc_label.insets = new Insets(0, 0, 0, 5);
		gbc_label.gridx = 0;
		gbc_label.gridy = 2;
		inputPanel.add(label, gbc_label);
		
		fileNameField = new JTextField();
		fileNameField.setEditable(false);
		fileNameField.setColumns(10);
		GridBagConstraints gbc_fileNameField = new GridBagConstraints();
		gbc_fileNameField.fill = GridBagConstraints.HORIZONTAL;
		gbc_fileNameField.gridx = 1;
		gbc_fileNameField.gridy = 2;
		inputPanel.add(fileNameField, gbc_fileNameField);
		
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBounds(125, 322, 483, 57);
		mainPanel.add(buttonPanel);
		buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 5));
		
		inputButton = new JButton("输入成绩");
		inputButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				subjectName = StringUtils.trim(subjectField.getText()) ;
				className = StringUtils.trim(classField.getText());
				subjectField.setText(subjectName) ;
				classField.setText(className) ;
				
				if(StringUtils.isBlank(subjectName)) {
					MessageUtil.showMessage(self, Constant_msg.SUBJECT_INPUT_ERR) ;
					return ;
				} else if(StringUtils.isBlank(className)) {
					MessageUtil.showMessage(self, Constant_msg.CLASS_INPUT_ERR) ;
					return ;
				}
				currFile = excelService.openExcel(subjectName, className) ;
				fileNameField.setText(currFile.getAbsolutePath()) ;
			}
		});
		inputButton.setPreferredSize(new Dimension(90, 30));
		buttonPanel.add(inputButton);
		
		openButton = new JButton("打开文件");
		
		openButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				subjectName = StringUtils.trim(subjectField.getText()) ;
				className = StringUtils.trim(classField.getText());
				subjectField.setText(subjectName) ;
				classField.setText(className) ;
				
				if(StringUtils.isBlank(subjectName)) {
					MessageUtil.showMessage(self, Constant_msg.SUBJECT_INPUT_ERR) ;
					return ;
				} else if(StringUtils.isBlank(className)) {
					MessageUtil.showMessage(self, Constant_msg.CLASS_INPUT_ERR) ;
					return ;
				}
				
				fChooser.showOpenDialog(self);
				currFile = fChooser.getSelectedFile() ;
				if(currFile == null) {
					return ;
				}
				log.info("select file :" + (currFile == null ? "null" : currFile.getAbsolutePath()) ) ;
				if(!currFile.exists()){
					MessageUtil.showMessage(self, "您选择的文件格式不正确!") ;
				}
				fileNameField.setText(currFile.getAbsolutePath()) ;
			}
		});
		openButton.setPreferredSize(new Dimension(90, 30));
		buttonPanel.add(openButton);
		
		analyzeButton = new JButton("分析");
		analyzeButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(currFile == null ) {
					MessageUtil.showMessage(self, Constant_msg.NO_DATA_ANALYZE ) ;
					return ;
				}
				Configuration configuration = AppContext.getConfiguration() ;
				 Model readModel = excelService.readExcel(currFile , configuration.getScoreList());
				 if(readModel.hasErr()) {
					 MessageUtil.showMessage(self, readModel.getErr().get(0).toString()) ;
					 return ;
				 }
				 List<Map<String , Object>> list = readModel.getAttrbute(Constant.READ_EXCEL_RESULT_LIST_KEY) ;
				 Model model = analyzeService.analize(list, configuration) ;
				 File chartFile = chartService.createChart(configuration , model) ;
				 Model resultModel = excelService.createExcel(model, chartFile , className , subjectName) ;
				 try {
					Desktop.getDesktop().open((File) resultModel.getAttrbute(Constant.RESULT_FILE_KEY)) ;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		analyzeButton.setPreferredSize(new Dimension(70, 30));
		buttonPanel.add(analyzeButton);
		
		setupButton = new JButton("系统设置");
		setupButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				SetupView sv = new SetupView(self , true) ;
				sv.setVisible(true) ;
			}
		});
		setupButton.setPreferredSize(new Dimension(90, 30));
		buttonPanel.add(setupButton);
	}

	public ExcelService getExcelService() {
		return excelService;
	}

	public void setExcelService(ExcelService excelService) {
		this.excelService = excelService;
	}

	public File getCurrFile() {
		return currFile;
	}

	public void setCurrFile(File currFile) {
		this.currFile = currFile;
	}

	public AnalyzeService getAnalyzeService() {
		return analyzeService;
	}

	public void setAnalyzeService(AnalyzeService analyzeService) {
		this.analyzeService = analyzeService;
	}

	public ChartService getChartService() {
		return chartService;
	}

	public void setChartService(ChartService chartService) {
		this.chartService = chartService;
	}
}
